package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Concensus;
import com.woyao.core.model.GetConcensusResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;


public class ConcensusEditActivity extends AppCompatActivity {

    private TextView partnersTxt;

    private TextView agreeTxt;
    private TextView agreeElseTxt;

    private EditText durationTxt;
    private TextView myDutyTxt;
    private TextView relationDutyTxt;
    private Button actButton;
    private TextView memoTxt;

    private ImageView idcardImg;
    private ImageView buzzcardImg;
    private ImageView relation_idcardImg;
    private ImageView relation_buzzcardImg;


    private  Button nextBtn;

    ProgressDialog progressDialog;
    Concensus concensus = new Concensus();

    Integer id = 0;

    private Integer AGREEMENT_CODE = 500;
    private Integer AGREEMENT_ELSE_CODE = 600;
    private Integer RIGHT_DUTY_CODE = 700;
    private Integer RELATION_RIGHT_DUTY_CODE = 800;

    private ClipboardManager myClipboard;
    private ClipData myClip;

    private boolean loading = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_concensus_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout



        idcardImg = (ImageView) findViewById(R.id.id_user_idcard);
        buzzcardImg = (ImageView) findViewById(R.id.id_user_buzzcard);
        relation_idcardImg = (ImageView) findViewById(R.id.id_relation_idcard);
        relation_buzzcardImg = (ImageView) findViewById(R.id.id_relation_buzzcard);


        idcardImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(ConcensusEditActivity.this, WebviewActivity.class);
                intent.putExtra("title", "用户帮助");
                intent.putExtra("link", concensus.getIdcard());
                startActivity(intent);
            }
        });

        relation_idcardImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(ConcensusEditActivity.this, WebviewActivity.class);
                intent.putExtra("title", "用户帮助");
                intent.putExtra("link", concensus.getRelation_idcard());
                startActivity(intent);
            }
        });
        buzzcardImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(ConcensusEditActivity.this, WebviewActivity.class);
                intent.putExtra("title", "用户帮助");
                intent.putExtra("link", concensus.getBuzzcard());
                startActivity(intent);
            }
        });

        relation_buzzcardImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(ConcensusEditActivity.this, WebviewActivity.class);
                intent.putExtra("title", "用户帮助");
                intent.putExtra("link", concensus.getRelation_buzzcard());
                startActivity(intent);
            }
        });

        partnersTxt  = (TextView) findViewById(R.id.concensus_partners);

        durationTxt  = (EditText) findViewById(R.id.id_concensus_duration);

        durationTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (loading ) {
                    return;
                }
                try{
                    concensus.setDuration(Float.parseFloat(durationTxt.getText().toString() ));
                    Common.setConcensusAttrFeedback( ConcensusEditActivity.this, concensus.getId(), "duration", concensus.getDuration() + "");
                }catch(Exception e) {
                    Common.alert(ConcensusEditActivity.this, "请输入合理的数字");
                    durationTxt.requestFocus();
                    durationTxt.selectAll();
                }


            }
        });
        memoTxt  = (TextView) findViewById(R.id.concensus_memo);

        actButton = (Button) findViewById(R.id.concensus_act);

        actButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog alertDialog = new AlertDialog.Builder(ConcensusEditActivity.this).
                        setTitle("操作").
                        setMessage("").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dosth();
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();


            }
        });

        agreeTxt = (TextView) findViewById(R.id.concensus_agreement);

        agreeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( !concensus.getChangable()) {
                    Common.alert(ConcensusEditActivity.this, "已经确认，不可以更改");
                    return;
                }

                Intent intent = new Intent();
                intent.putExtra("type","agreement");
                intent.putExtra( "content", concensus.getAgreement() );
                intent.setClass(ConcensusEditActivity.this,  InputActivity.class);
                startActivityForResult(intent,AGREEMENT_CODE);

            }
        });

        agreeElseTxt = (TextView) findViewById(R.id.concensus_agree_else);

        agreeElseTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (  !concensus.getChangable()) {
                    Common.alert(ConcensusEditActivity.this, "已经确认，不可以更改");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("type","agreement_else");
                intent.putExtra( "content", concensus.getAgreement_else() );
                intent.setClass(ConcensusEditActivity.this,  InputActivity.class);
                startActivityForResult(intent,AGREEMENT_ELSE_CODE);

            }
        });

        myDutyTxt = (TextView) findViewById(R.id.right_duty);

        myDutyTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (  !concensus.getChangable()) {
                    Common.alert(ConcensusEditActivity.this, "已经确认，不可以更改");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("type","right_duty");
                intent.putExtra( "content", concensus.getRight_duty() );
                intent.setClass(ConcensusEditActivity.this,  InputActivity.class);
                startActivityForResult(intent,RIGHT_DUTY_CODE);

            }
        });


        relationDutyTxt = (TextView) findViewById(R.id.concensus_relation_right_duty);

        relationDutyTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (  !concensus.getChangable()) {
                    Common.alert(ConcensusEditActivity.this, "已经确认，不可以更改");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("type","relation_right_duty");
                intent.putExtra( "content", concensus.getRelation_right_duty() );
                intent.setClass(ConcensusEditActivity.this,  InputActivity.class);
                startActivityForResult(intent,RELATION_RIGHT_DUTY_CODE);

            }
        });


        Button viewButton = (Button) findViewById(R.id.view_concensus);

        viewButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("id",id);
                intent.setClass(ConcensusEditActivity.this,  ConcensusActivity.class);
                startActivity(intent);

            }
        });


        nextBtn = (Button) findViewById(R.id.concensus_edit_finish);

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               finish();
            }
        });

        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        loadData();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", true );
        setResult(0, intent);
        finish();
        return true;
    }


    private void dosth(){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> needTask = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.actConcensus(userId, concensus.getId(),concensus.getAct());
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null ) {
                    if (!response.getMessage().equals("")){
                        afterDo(  response );
                    }
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void) null);
    }

    private void afterDo( BaseResponse response ){

        Dialog alertDialog = new AlertDialog.Builder(ConcensusEditActivity.this).
                setTitle("信息").
                setMessage(response.getMessage()).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        loadData();
                    }
                }).
                create();
        alertDialog.show();
    }

    private void loadData() {

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetConcensusResponse> needTask = new AsyncTask<Void, Void, GetConcensusResponse>() {
            @Override
            protected GetConcensusResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetConcensusResponse> responseCall = svc.getConcensus(userId, id);
                try {
                    GetConcensusResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final GetConcensusResponse response) {
                if (response != null && response.getContent() != null) {
                    concensus = response.getContent();
                    if (!response.getMessage().equals("")) {
                        Common.alert(ConcensusEditActivity.this, response.getMessage());
                    }

                    renderIt( );
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void) null);
    }

    private void renderIt() {
        loading = true;

        this.setTitle( "合作共识");

        if (  !concensus.getChangable()) {
            durationTxt.setEnabled( false );
        }else{
            durationTxt.setEnabled( true );
        }

        actButton.setText( concensus.getAct_text());

        partnersTxt.setText(concensus.getPartners());


        memoTxt.setText(concensus.getMemo());

        if (!concensus.getAgreement().equals("")) {
            agreeTxt.setText(concensus.getAgreement());
            agreeTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        }

        if (!concensus.getAgreement_else().equals("")) {
            agreeElseTxt.setText(concensus.getAgreement_else());
            agreeElseTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        }

        if (!concensus.getDuration().equals("")) {
            durationTxt.setText(concensus.getDuration()+"");
            durationTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        }

        if (!concensus.getRight_duty().equals("")) {
            myDutyTxt.setText(concensus.getRight_duty());
            myDutyTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        }

        if (!concensus.getRelation_right_duty().equals("")) {
            relationDutyTxt.setText(concensus.getRelation_right_duty());
            relationDutyTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        }

        if (concensus.getAct_text().equals("")){
            actButton.setVisibility(View.GONE);
        }


        if (StringUtil.notNullOrEmpty(concensus.getIdcard())) {
            Picasso.with(this)
                    .load(concensus.getIdcard_snail())
                    .into(idcardImg);
        }

        if (StringUtil.notNullOrEmpty(concensus.getBuzzcard())) {
            Picasso.with(this)
                    .load(concensus.getBuzzcard_snail())
                    .into(buzzcardImg);
        }
        if (StringUtil.notNullOrEmpty(concensus.getRelation_idcard())) {
            Picasso.with(this)
                    .load(concensus.getRelation_buzzcard_snail())
                    .into(relation_idcardImg);
        }
        if (StringUtil.notNullOrEmpty(concensus.getRelation_buzzcard())) {
            Picasso.with(this)
                    .load(concensus.getRelation_buzzcard_snail())
                    .into(relation_buzzcardImg);
        }

        loading = false;
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == AGREEMENT_CODE && resultCode == 666) {
            CharSequence con = data.getCharSequenceExtra("content");

            concensus.setAgreement( con.toString());
            agreeTxt.setText(con);
            agreeTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));

            Common.setConcensusAttrFeedback( ConcensusEditActivity.this, concensus.getId(),"agreement", con.toString());

        }

        if (requestCode == AGREEMENT_ELSE_CODE && resultCode == 666) {
            CharSequence con = data.getCharSequenceExtra("content");

            concensus.setAgreement_else( con.toString());
            agreeElseTxt.setText(con);
            agreeElseTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
            Common.setConcensusAttrFeedback( ConcensusEditActivity.this, concensus.getId(),"agreement_else", con.toString());

        }


        if (requestCode == RIGHT_DUTY_CODE && resultCode == 666) {
            CharSequence con = data.getCharSequenceExtra("content");

            concensus.setRight_duty( con.toString());
            myDutyTxt.setText(con);
            myDutyTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
            Common.setConcensusAttrFeedback( ConcensusEditActivity.this, concensus.getId(),"right_duty", con.toString());

        }


        if (requestCode == RELATION_RIGHT_DUTY_CODE && resultCode == 666) {
            CharSequence con = data.getCharSequenceExtra("content");

            concensus.setRelation_right_duty( con.toString());
            relationDutyTxt.setText(con);
            relationDutyTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
            Common.setConcensusAttrFeedback( ConcensusEditActivity.this, concensus.getId(),"relation_right_duty", con.toString());

        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", true );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}